/* =============================== */
/* = General Hover-related tasks = */
/* =============================== */

var Hover = {
  EXIT_DELAY  : 600,
  HOVER_BG_ON : 'url(/images/hover-gradient.gif) left repeat-y',
  HOVER_BG_OFF: 'none',
  
  lastTimer   : null,
  lastCommand : null,
  inhibit     : false,
  
  clearCurrent: function() {
    if(!this.lastTimer) return
    clearTimeout(this.lastTimer)
    eval(this.lastCommand)
    this.lastTimer = this.lastCommand = null
  },
  
  endWith: function(command) {
    if(this.inhibit) return
    this.lastCommand = command
    this.lastTimer = setTimeout(command, this.EXIT_DELAY)
  },
  
  toggle: function(on, container, nubbin) {
    if(this.inhibit) return
    
    if(on) {
      if($(container))
        $(container).style.background = this.HOVER_BG_ON
      Element.showIf(nubbin)
    } else {
      if($(container))
        $(container).style.background = this.HOVER_BG_OFF
      Element.hideIf(nubbin)
    }
  }
}


/* ============================================ */
/* = Tasks relating to individual to-do items = */
/* ============================================ */

var todos = {
  
  reorder: {
    toggle: function(id) {
      
      Element.toggle('non_reorderable');
      
      // activate the link (changes the text and class of the link)
      var link = $('reorder_list_' + id + '_link')
      Element.activate(link, !link['bc:active'])
      if (link['bc:active']) {
        todos.makeDraggable(id)        
      }
      // don't hover when a reorder request is active
      Hover.inhibit = link['bc:active']

      // toggle the checkbox and the drag icon for each item
      $$('ul#incompleted li').each(function(element) {
        var id = element.id;
        Element.toggle('check_box_for_' + id)
        if ($('drag_' + id)) Element.toggle('drag_' + id)        
      })
    }
  },

  makeDraggable: function(id) {
    Sortable.create($('incompleted'), {handle: 'di_' + id});
    this.installDragObserver();
  },

  installDragObserver: function() {
    if (!this.observer_installed) {
      this.observer_installed = true
      Draggables.addObserver({
        onStart: function(name, draggable, event) {},
        onEnd: function(name, draggable, event) {
          var element  = draggable.element;
          var siblings = todos.siblingsOf(element);
          var position = siblings.indexOf(element) + 1;

          var parms = "id=" + todos.idOf(element) + "&to=" + position
          new Ajax.Request(item_reorder_url, { parameters: parms, asynchronous: true })
        }
      })
    }
  },

  idOf: function(element) {
    return element.id.split("_").last();
  },

  siblingsOf: function(element) {
    return $A(element.parentNode.childNodes).select(function(sibling) {
      return sibling.tagName == element.tagName;
    })
  }
}
